#include <stdio.h>
#include <stdint.h>

#include <sys/times.h>

#define K_MS        1U
#define APP_DELAY_LIMIT (uint32_t)0xff000000U

/*系统的时间片大小，一般是10MS 或者 1MS*/
#define TICKS_PER_SEC 10 

static uint32_t app_get_systime(void)
{
    uint32_t t = (uint32_t)times(0);
	return t;
}

/* 软件定时器睡眠nms */
void app_sleep(volatile uint32_t *pt_cnt, uint32_t ums) {
    if( (ums > 0) && (ums < APP_DELAY_LIMIT) ) {
        *pt_cnt= app_get_systime()+ ums;
    }
}

/* 判断软件定时器是否到期 */
uint8_t app_pend_wake(uint32_t pt_cnt) {
    uint32_t off = app_get_systime() - pt_cnt;
    if( off < APP_DELAY_LIMIT ) {
        return 1;
    }
    return 0;
}

uint8_t app_capture_interval(uint32_t pt_cnt, uint32_t u_ms) { 
    uint32_t off = app_get_systime() - pt_cnt - u_ms*K_MS;
	printf("off is %x / %x\r\n", off, APP_DELAY_LIMIT);
    if( off < APP_DELAY_LIMIT ) {
        return 1;
    }
    return 0;
}

void app_update_interval(volatile uint32_t *ptcnt) {
	*ptcnt = app_get_systime();
}


int main(int argc, char** argv) {
	volatile uint32_t tick = 0;
	
	while(1) {
		if( app_capture_interval(tick, 100) ) {
			app_update_interval(&tick);
			printf("tick is %d\r\n", tick);
		}
		usleep(200*1000);
		
	}
	
	
}
